package cn._2dland.bots.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn._2dland.bots.TaskManager;
import cn._2dland.bots.U115Bot;
import cn._2dland.bots.jdo.AccountManager;
import cn._2dland.bots.jdo.PickRecordManager;
import cn._2dland.bots.jdo.models.Account;

@SuppressWarnings("serial")
public class BotServlet extends HttpServlet {
	public static final int ACTION_PICK = 1;
	public static final int ACTION_RENEW = 2;
	
	public static final int MAX_LOGIN_RETRY = 10;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// 参数处理
		String acctIdStr = req.getParameter("accountID");
		String actionStr = req.getParameter("action");

		AccountManager am = new AccountManager();
		resp.setContentType("text/plain; charset=utf-8");
		try {
			// 参数处理
			if(acctIdStr == null || !acctIdStr.matches("^\\d+$"))
				throw new Exception("无效帐户ID！");
			if(actionStr == null || !actionStr.matches("^[1-2]$"))
				throw new Exception("无效动作编号！");

			// 读取帐户信息
			Long acctId = Long.valueOf(acctIdStr);
			Account acct = am.getAccount(acctId);
			if(acct == null)
				throw new Exception("该帐户不存在！");
			if(acct.getStatus() != Account.STATUS_ACTIVE)
				throw new Exception("该帐户已停用！");

			// 构造机器人
			U115Bot bot = new U115Bot(acct.getUsername(), acct.getPassword());
			// 尝试登录
			for(int failed=0; failed<MAX_LOGIN_RETRY && !bot.login(); failed++);
			if(!bot.isLogin()) {
				// 连续登录失败时，将账户标记为失败
				AccountManager.setStatus(acctId, Account.STATUS_ERROR);
				throw new Exception("超过最大重试登录次数！");
			}

			switch(Integer.parseInt(actionStr)){
			case ACTION_PICK:
				int picked = bot.pick();
				if(picked < 0) {
					throw new ServerException("领取时发生错误！");
				} else if(picked > 0) {
					// 正常领取到空间时，进行记录
					PickRecordManager.logPick(acctId, picked);
				}
				TaskManager.createTask(acctId, ACTION_PICK);
				break;
			case ACTION_RENEW:
				bot.renew(0);
				bot.renew(1);
				TaskManager.createTask(acctId, ACTION_RENEW);
				break;
			}

			// 更新帐户最后活动时间
			AccountManager.updateLastTime(acctId);

			// 输出信息
			resp.getWriter().println("操作执行成功！");
		}
		catch (Exception e) {
			e.printStackTrace(resp.getWriter());
			if(e instanceof ServerException)
				resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}
		finally {
			am.close();
		}
	}
}
